package com.xpmusic.controller.admin;

import com.xpmusic.dao.impl.AdminDaoImpl;
import com.xpmusic.model.AdminInfo;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 过滤除管理员之外其他任何访问
 * 保护后台安全
 */
public class AdminFilter implements Filter {
    public void destroy() {
    }
    
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest request= (HttpServletRequest) req;
        HttpServletResponse response= (HttpServletResponse) resp;
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //PrintWriter out=response.getWriter();
        AdminInfo adminInfo = (AdminInfo) request.getSession().getAttribute("admin");
        if (adminInfo==null){
            response.getWriter().write("你尚未登录或登录已失效！");
            return;
        }
        //验证用户权限
        boolean i = new AdminDaoImpl().checkAdminInfo(adminInfo);
        String referer=request.getHeader("Referer");
        String sitePart="http://"+request.getServerName();//获取发送请求的服务器的主机名
        //判断referer是否为空，这个头的首地址是否以sitePart开始的
        if (referer!=null && referer.startsWith(sitePart)){
            if (i){//管理员
                chain.doFilter(request, response);
            } else{
                response.getWriter().write("你尚未登录或登录已失效！");
            }
        }else{
            response.getWriter().write("你尚未登录或登录已失效！");
        }
    }
    
    public void init(FilterConfig config) throws ServletException {
    }
}
